<!-- eslint-disable vue/multi-word-component-names -->
<script setup lang="ts">
const scrollContainer = ref<HTMLElement | null>(null);
const items = ref([
    { id: 1, text: 'Item 1' },
    { id: 2, text: 'Item 2' },
    { id: 3, text: 'Item 3' },
    { id: 4, text: 'Item 4' },
    { id: 5, text: 'Item 5' },
    { id: 6, text: 'Item 6' },
    // 添加更多的项目
]);
// 定义开始向右滚动的方法
function startScrolling() {
    if (scrollContainer.value) {
        scrollToRight();
    }
}

// 定义缓慢向右滚动的方法
function scrollToRight() {
    if (scrollContainer.value) {
        const container = scrollContainer.value;
        const scrollAmount = 1; // 每次滚动的距离
        const delay = 10; // 延迟时间

        const scroll = () => {
            container.scrollLeft += scrollAmount;
            // console.log('container.scrollLeft', container.scrollLeft);
            if (container.scrollLeft % 420 === 0) {
                // const firstItem = items.value.shift();
                // console.log('items', firstItem);
                items.value.push(items.value[container.scrollLeft / 420 - 1]);
                // console.log('items', items, container.scrollLeft / 400);
            }
            if (items.value.length === 12) {
                items.value = items.value.slice(6);
                container.scrollLeft = 0; // 重置滚动位置
            }
            requestAnimationFrame(scroll);
        };

        // 开始滚动
        setTimeout(scroll, delay);
    }
}
// 处理滚动结束
function handleScrollEnd() {
    if (scrollContainer.value) {
        const container = scrollContainer.value;
        const firstItem = items.value.shift();
        items.value.push(firstItem!);
        container.scrollLeft = 0; // 重置滚动位置
        startScrolling(); // 开始下一次滚动
    }
}
// 在组件挂载后滚动到最右边
onMounted(() => {
    scrollToRight();
    // if (scrollContainer.value) {
    //     const container = scrollContainer.value;
    //     container.addEventListener('scroll', () => {
    //         if (
    //             container.scrollLeft ===
    //             container.scrollWidth - container.clientWidth
    //         ) {
    //             handleScrollEnd();
    //         }
    //     });
    // }
});
</script>
<template>
    <header class="header">
        <div ref="scrollContainer" class="scroll-header">
            <div v-for="item in items" :key="item.id">
                <div class="scroll-box">
                    <div>样式卡：{{ item.text }}</div>
                </div>
            </div>
        </div>
    </header>
</template>

<style lang="scss" scoped>
.scroll-header {
    width: 92%;
    left: 4%;
    top: 67%;
    position: absolute;
    height: 250px;
    overflow-y: auto;
    display: flex;
    .scroll-box {
        width: 400px;
        border: 1px solid;
        height: 100%;
        margin-left: 20px;
    }
}
@keyframes scroll {
    to {
        transform: translateX(-100%);
    }
}
</style>
